<?php

namespace Modules\Code\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Code\Entities\Code;
use Modules\Code\Exports\CodeExport;

use Auth;
use Validator;
use ThrowException;

use Cache;

class CodeExportController extends Controller
{
    public function total(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $options = $req->all();

        $total = Code::getList($options, false)->builder->count();

        return [
            'total' => $total
        ];
    }

    public function store(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();


        $uuid = str_random(30);

        $cached = $req->all();

        Cache::put($uuid, $cached, 10);

        return [
        	'url' => '/admin-api/export/codes/' . $uuid
        ]; 
    }

    public function show(Request $req, $uuid)
    {
    	$rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $cached = Cache::get($uuid) ?: ThrowException::Conflict('未找到缓存内容');

        $cached['per_page'] = 1000000;
        
        $orders = Code::getList($cached)->list;

        $file = '激活码导出.xlsx';
        return (new CodeExport($orders))->download($file); 
    }
}
